#include<iostream>
#include<string>
#include<functional>
#include<vector>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
using namespace std;
using func_t=function<void()>;
const int threadnum=5;
class ThreadData
{
    public:
    ThreadData(const string&name,const uint64_t&ctime,func_t f)
    :threadname(name)
    ,createtime(ctime)
    ,func(f)
    {}
    public:
    string threadname;
    uint64_t createtime;
    func_t func;
};
class ThreadReturn
{
    public:
    ThreadReturn(pthread_t id,int code,string info)
    :_id(id)
    ,_code(code)
    ,_info(info)
    {}
    public:
    pthread_t _id;
    int _code;
    string _info;
};
string to_Hex(pthread_t tid)
{
    char id[64];
    snprintf(id,sizeof id,"0x%x",tid);
    return id;
}
void *ThreadRoutine(void*args)
{
    pthread_detach(pthread_self());
    int a=10;
    ThreadData*td=static_cast<ThreadData*>(args);
    while(a--)
    {
        cout<<"I am new Thread  "<<td->threadname<<' '<<td->createtime<<' '<<to_Hex(pthread_self())<<' '<<endl;
        //td->func();
        // if(td->threadname=="thread-4")
        // {
        //     a/=0;
        // }
        sleep(1);
    }
    //ThreadReturn* ret=new ThreadReturn(pthread_self(),10,"quit normal");
    //pthread_exit((void*)ret);
    return nullptr;

}
void print()
{
    cout<<"我是线程执行的大任务的一部分"<<endl;
}


int main()
{
  
    pthread_t tid;
    char threadname[64];
    snprintf(threadname,sizeof threadname,"%s-%d","thread",1);
    ThreadData*td=new ThreadData(threadname,uint64_t(time(nullptr)),print);

    pthread_create(&tid,nullptr,ThreadRoutine,td);
    //pthread_detach(tid);
    sleep(3);
    int n=pthread_cancel(tid);
    cout<<"pthread cancel : n"<<n<<endl;
    cout<<to_Hex(tid)<<endl;
    void *ret=nullptr;
    n=pthread_join(tid,&ret);
    // ThreadReturn*r=static_cast<ThreadReturn*>(ret);
    cout<<"main thread done"<<"   n:   "<<n<<' '<<(int64_t)ret<<endl;
   // cout<<r->_id<<' '<<r->_code<<' '<<r->_info<<endl;
    return 0;

}
